from sqlmodel import SQLModel
from database.mysql import AsyncSessionLocal
from typing import List, Optional
from sqlalchemy.orm import load_only

from schemas.common import Filter
from server.Base import BaseServer

class SystemServer(BaseServer):
    def __init__(self, model: SQLModel):
        super().__init__(model)  # 调用父类的构造函数

    async def getDeptAll(self, filters: Optional[List[Filter]] = [], fields: Optional[List[str]] = None):
        async with AsyncSessionLocal() as session:  # 使用异步会话
            query = await self.build_query(filters)

            options = []
            # 如果指定了 fields，则构建只查询特定字段的查询
            if fields:
                options.append(load_only(*[getattr(self.model, field) for field in fields]))

            # 添加选项到查询
            query = query.options(*options)
            results = await session.execute(query)  # 使用 await 以异步方式执行查询
            return results.scalars().all()

    async def get_dept_child_ids(self, parent_id: int):
        dept_ids = await self.get_dept_child_ids_loop(parent_id, [])
        return dept_ids

    async def get_dept_child_ids_loop(self, parent_id: int, dept_ids: List[int] = None):
        dept_ids.append(parent_id)
        async with AsyncSessionLocal() as session:  # 使用异步会话
            query = await session.execute(self.model.parentId == parent_id)  # 异步执行查询
            results = query.scalars().all()
            
            if results:
                for result in results:
                    dept_ids.append(result.id)
                    dept_ids = await self.get_dept_child_ids_loop(result.id, dept_ids)

        return dept_ids
